package jcer.task;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import net.sf.json.JSONArray;

import jcer.core.*;
import jcer.task.util.SqlHelper;

public class SqlTask extends Task {
	static Log logger = LogFactory.getLog(SqlTask.class);

	String key;
	String sql;

	static {
		try {
			SqlHelper.sourceMap = new HashMap<String, ArrayList<ComboPooledDataSource>>();

			Configuration config = new PropertiesConfiguration(
					"./conf/sqltask.properties");
			for (int i = 0;; i++) {
				Configuration sourceConfig = config.subset("db.source."
						+ ((Integer) i).toString());
				if (sourceConfig.isEmpty()) {
					break;
				}
				String sourceKey = sourceConfig.getString("key").trim();
				ComboPooledDataSource source = new ComboPooledDataSource();
				source.setDriverClass(sourceConfig.getString("driver"));
				source.setJdbcUrl(sourceConfig.getString("jdbcUrl"));
				source.setUser(sourceConfig.getString("user"));
				source.setPassword(sourceConfig.getString("password"));
				source.setMinPoolSize(sourceConfig.getInt("minPollSize"));
				source.setAcquireIncrement(sourceConfig
						.getInt("acquireIncrement"));
				source.setMaxPoolSize(sourceConfig.getInt("maxPoolSize"));

				if (!SqlHelper.sourceMap.containsKey(sourceKey)) {
					ArrayList<ComboPooledDataSource> sourceList = new ArrayList<ComboPooledDataSource>();
					SqlHelper.sourceMap.put(sourceKey, sourceList);
				}
				SqlHelper.sourceMap.get(sourceKey).add(source);
			}
		} catch (Exception e) {

		}
	}

	@Override
	public void decode(ByteBuffer buf) throws Exception {
		logger.debug("decode task");
		byte[] msgBuf = new byte[buf.remaining()];
		buf.get(msgBuf);
		String tmp = new String(msgBuf, "utf-8");
		int pos = tmp.indexOf(':');
		if (pos < 0) {
			throw new Exception("Request Is Invalid");
		}
		key = tmp.substring(0, pos);
		sql = tmp.substring(pos + 1);
	}

	@Override
	public byte[] comsume() {
		logger.debug("comsume task");
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			SqlHelper sqlHelper = new SqlHelper(key);
			List<HashMap<String, String>> data = sqlHelper.query(sql);
			logger.info(sql);
			result.put("status", 0);
			result.put("msg", "");
			result.put("data", data);
		} catch (Exception e) {
			result.put("status", 500);
			result.put("msg", e.getMessage());
		}
		JSONArray jsonArray = JSONArray.fromObject(result);
		String response = jsonArray.toString();

		try {
			byte[] data = response.getBytes("utf-8");
			return data;
		} catch (UnsupportedEncodingException e) {
			return new byte[0];
		}
	}

}
